//
//  NewsDetail.swift
//  newsApp
//
//  Created by Doo Psyist on 2020/5/12.
//  Copyright © 2020 Doo Psyist. All rights reserved.
//

import SwiftUI
import MessageUI


var currentId: Int!
var currentStreet: Street!
var currentIndex: Int!
class NewsComments: ObservableObject { //dynamically load comments
    @Published var newsComments: Array<String> = []
    func load(id: Int) {
        newsComments = loadComment(id: id)
    }
}
struct Street: Identifiable, Hashable { //comments list
    var id = UUID()
    var comment: String
    var nid:Int
}
struct StreetRow: View {
    var street: Street
    var body: some View {
        VStack(alignment: .leading) {
            Text("dukalee@foxmail.com")
                .font(.headline)
            HStack {
                Text(street.comment)
                    .font(.subheadline)
            }

        }
    }
}

struct NewsDetail: View {
    @State var showAlert = false
    @State var showPop = false
    @State var isLiked = false
    @ObservedObject var comments = NewsComments()
    @State var commentArray: Array<String>
    @State var streets: Array<Street> = []
    var newsListItem: NewsListItem
    @Environment(\.presentationMode) var presentation
    var body: some View {
        ScrollView(.vertical) {
            VStack(alignment: .leading) {
                HStack {
                    Text(newsListItem.title)
                        .font(.system(size: 30, design: .rounded))
                        .bold()
                        .shadow(radius: 1)
                        .foregroundColor(Color.orange)
                    Spacer()
                    Button(action: {
                        self.shareNews()
                        
                    }){
                        Image(systemName: "paperplane.fill")
                        .foregroundColor(.blue)
                        .imageScale(.large)
                        .shadow(radius: 1)
                    }
                    Button(action: {
                        if self.isLiked == false {
                            if updateLike(id: self.newsListItem.id, isLiked: true) == true {
                                self.isLiked = true
                            }
                        } else if self.isLiked == true {
                            if updateLike(id: self.newsListItem.id, isLiked: false) == true {
                                self.isLiked = false
                            }
                        }
                    }) {
                        Image(systemName: self.isLiked == true ? "hand.thumbsup.fill" : "hand.thumbsup")
                            .foregroundColor(.blue)
                            .imageScale(.large)
                            .shadow(radius: 1)

                    }.onAppear() {

                        self.isLiked = findNewsbyId(self.newsListItem.id)[0].like
                        print(self.isLiked)
                    }

                }

                HStack {
                    Text(newsListItem.summary)
                        .font(.headline)
                    Spacer()
                    Text(newsListItem.date)
                        .font(.subheadline)
                }
                    .padding(.bottom, 20)
                
                
                MapView(newsListItem: newsListItem)
                    .frame(height:200)
                    .padding(.top,0)
                
                VStack(alignment: .leading) {
                    Text(newsListItem.content)
                        .font(.title)
                        .padding(.bottom, 8)
                }
                    .padding(.bottom, 20)
                    .frame(height: 500)
                

                VStack(alignment: .leading) {
                    HStack {
                        Image(systemName: "pencil.and.ellipsis.rectangle")
                        //.imageScale(.large)
                        .foregroundColor(.blue)
                            .shadow(radius: 1)


                        Text("评论").bold()
                    }
                    List() { ForEach(streets) { street in
                            HStack {
                                StreetRow(street: street).onAppear() {
                                    currentStreet = street
                                }

                                Spacer()
                                Button(action: {
                                    self.showAlert = true
                                }) {
                                    Image(systemName: "trash")
                                }
                                    .alert(isPresented: self.$showAlert, content: {
                                        Alert(title: Text("确定要删除评论吗？"),
                                            message: Text("请谨慎操作\n一旦确认，无法恢复"),
                                            primaryButton: .destructive(Text("确认")) {

                                                deleteComment(street: street)
                                                self.deleteRow1(at: self.streets.firstIndex(of: street)!)

                                            },
                                            secondaryButton: .cancel()
                                        )
                                    })
                            }.padding()
                                .background(Color.blue)
                                .cornerRadius(20)
                                .shadow(radius: 10)

                        }
                    }.onAppear() {
                        self.streets = commentStreets(val: self.commentArray)
                    }
                }.padding(.bottom, 20)




                /*
                 VStack(alignment: .leading) {
                 Text("评论")
                 .font(.title)
                 .padding(.bottom, 8)
                 VStack(alignment: .leading) {
                 Text("用户1")
                 .font(.headline)
                 Text(commentArray.isEmpty ? " ":commentArray[0])
                 .font(.subheadline)
                 }
                 .padding(.bottom, 8)
                 }
                 .padding(.bottom, 20)
                 Spacer()
                 */
            }
                .padding()
                .navigationBarItems(trailing: NavigationLink(destination:
                        NewsComment(newsListItem: self.newsListItem)
                    , label: {
                        Image(systemName: "text.bubble.fill")
                            .imageScale(.large)
                            .accessibility(label: Text("Right"))
                            .padding()
                    }))
                .frame(height: 1500)


        }
            .onAppear() {
                currentId = self.newsListItem.id
                var accesscount: Int16 = 0
                self.comments.load(id: self.newsListItem.id)
                self.commentArray = self.comments.newsComments
                self.isLiked = findNewsbyId(self.newsListItem.id)[0].like
                accesscount = findNewsbyId(self.newsListItem.id)[0].access
                _ = updateAccess(id: self.newsListItem.id, access: accesscount + 1)
                print(self.comments.newsComments)
        }
    }
    func deleteRow1(at offsets: Int) {
        print(offsets)
        streets.remove(at: offsets)
    }
    func shareNews() {
        var content = self.newsListItem.content
        content =  content.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) ?? ""
        let str:String = "sms://10086&body=\(content)"
        //print("sms://10086&body=\(self.newsListItem.content)")
        let url1 = NSURL(string: str)
        UIApplication.shared.open(url1! as URL)
    }
}
func commentStreets(val: Array<String>) -> Array<Street> {
    print(val)
    var i = 0
    var res = Array<Street>()
    val.forEach { (item) in
        res.append(Street(comment: val[i],nid:i))
        i = i + 1
    }
    print(res)
    return res
}
func deleteComment(street: Street) {
    let commentsArr = loadComment(id: currentId)
    var newComments: String = ""
    if commentsArr.contains(street.comment) {
//        commentsArr.forEach { (item) in
//            if item != street.comment {
//                newComments.append(item + "%%")
//            }
//        }
        for pis in 0..<commentsArr.count {
            if commentsArr[pis] != street.comment || pis != street.nid {
                newComments.append(commentsArr[pis] + "%%")
            }
        }
        _ = updateComments(id: currentId, comments: newComments)
    }

}





struct NewsDetail_Previews: PreviewProvider {
    static var previews: some View {
        NewsDetail(commentArray: ["111", "222"], newsListItem: newsList[0])
    }
}


